package top.cn27.luckyhe.mirai.plugin.residence;

import net.mamoe.mirai.console.command.CommandManager;
import net.mamoe.mirai.console.extension.PluginComponentStorage;
import net.mamoe.mirai.console.permission.Permission;
import net.mamoe.mirai.console.permission.PermissionId;
import net.mamoe.mirai.console.permission.PermissionRegistryConflictException;
import net.mamoe.mirai.console.permission.PermissionService;
import net.mamoe.mirai.console.plugin.jvm.JavaPlugin;
import net.mamoe.mirai.console.plugin.jvm.JvmPluginDescriptionBuilder;
import org.jetbrains.annotations.NotNull;
import top.cn27.luckyhe.mirai.plugin.residence.command.ResCommand;
import top.cn27.luckyhe.mirai.plugin.residence.utils.ConfigOperation;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class SpigotResidenceSolutionForCN27 extends JavaPlugin {

    public static final SpigotResidenceSolutionForCN27 INSTANCE = new SpigotResidenceSolutionForCN27();

    private Permission resPerm;

    private SpigotResidenceSolutionForCN27() {
        super(new JvmPluginDescriptionBuilder(
                "luckyhe.spigotresidencesolutionforcn27",
                "1.0"
        ).build());
    }

    @Override
    public void onLoad(@NotNull PluginComponentStorage $this$onLoad) {
        try {
            ConfigOperation.initConfigPath(getConfigFolder(), getResource("config.properties", StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onEnable() {
        INSTANCE.getLogger().info("开始加载插件");
        loadPermissions();
        INSTANCE.getLogger().info("注册权限完成");
        loadCommands();
        INSTANCE.getLogger().info("注册指令完成");
    }

    private void loadPermissions() {
        PermissionId resPermId = new PermissionId("spigotresidencesolutionforcn27", "command.res");
        try {
            resPerm = PermissionService.getInstance().register(
                    resPermId,
                    "领地相关指令（CN27专用）",
                    Permission.getRootPermission()
            );
        } catch (PermissionRegistryConflictException e) {
            e.printStackTrace();
        }
    }

    private void loadCommands() {
        String commandPrefix = CommandManager.INSTANCE.getCommandPrefix();

        String[] resCommandSecondaryNames = {"residence", "领地"};
        CommandManager.INSTANCE.registerCommand(new ResCommand(
                this,
                "res",
                resCommandSecondaryNames,
                commandPrefix + "res <操作>",
                "领地操作相关指令",
                resPerm,
                false
        ), false);
    }
}
